<?php
declare(strict_types=1);
/**
 * 自定义验证类异常处理
 * Created by PhpStorm.
 * User: 我想有个家
 * Date: 2020/4/13
 * Time: 17:21
 */

namespace App\Exception\Handler;


use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Validation\ValidationException;
use Psr\Http\Message\ResponseInterface;

class ValidationExceptionHandler extends ExceptionHandler {
    /**
     * @param ValidationException $throwable
     * @param ResponseInterface $response
     * @return mixed
     */
    public function handle($throwable, ResponseInterface $response) {
        $this->stopPropagation();
        $body = resData(10002, $throwable->validator->errors()->first(), new \stdClass());
        return $response->withStatus(200)
            ->withHeader('Content-Type', 'application/json')
            ->withBody(new SwooleStream(json_encode($body, JSON_UNESCAPED_UNICODE)));
    }

    public function isValid(\Throwable $throwable): bool {
        return $throwable instanceof ValidationException;
    }
}
